<template>
  <div>
    <content-panel
        ref="contentRef"
        title="管理员管理"
        :ops="contentOps"
        :search-props="searchProps"
        :table-props="tableProps"
        list-api="getAdminUsers"
        delete-api="deleteAdminUser"
        @handle-add="handleAdd"
        @handle-update="handleUpdate"
    >
      <template #avatar="scope">
        <el-image
            :preview-teleported="true"
            :preview-src-list="[scope.row.avatar?scope.row.avatar:$store.user.userInfo.avatar]"
            :src="scope.row.avatar?scope.row.avatar:$store.user.userInfo.avatar"
            style="width: 60px; height: 60px;border-radius: 30px;"
        />
      </template>

      <template #status="scope">
        <el-switch
            v-if="$xl.rolePerm.hasPerm('permission:user:edit')"
            v-model="scope.row.status"
            v-has-perm="['permission:user:edit']"
            active-value="0"
            inactive-value="1"
            style="display: block"
            @click="handleStatusChange(scope.row, 'status')"
        />
        <dict-tag v-else :options="$dict.normal_disable" :value="scope.row.status"/>
      </template>
      <template #operate="scope">
        <div class="operation-buttons">
          <el-button
              v-if="isCurScope"
              v-has-perm="['permission:user:edit']"
              size="small"
              link
              :icon="Edit"
              @click="handleUpdate(scope.row.id)"
          >修改
          </el-button>
          <el-button
              v-has-perm="['permission:user:remove']"
              size="small"
              link
              :icon="Delete"
              style="color: #F56C6C"
              @click="handleDelete(scope.row.id)"
          >删除
          </el-button>
          <el-dropdown
              v-has-perm="['permission:user:edit']"
              size="small"
              @command="(command) => handleCommand(command, scope.row)"
          >
            <el-button
                size="small"
                link
                :icon="DArrowRight"
                style="color: #23cf69"
            >更多
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item
                    command="handleResetPwd"
                    :icon="Key"
                >重置密码
                </el-dropdown-item>
                <el-dropdown-item
                    command="handleAuthRole"
                    :icon="User"
                >分配角色
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </template>

    </content-panel>

    <FormDialog
        ref="formDialog"
        :form-props="formProps"
        :width="45"
        :top="11"
        :height="50"
        @save="save"
        @update="update"
    />

    <FormDialog
        ref="roleFormDialog"
        :form-props="roleFormProps"
        :width="45"
        :top="11"
        :height="10"
        @save="saveRole"
    >
      <template #roleIds="scope">
        <el-select v-model="scope.row.roleIds" multiple placeholder="请选择">
          <el-option
              v-for="item in roleOptions"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
              :disabled="item.status === 1"
          />
        </el-select>
      </template>
    </FormDialog>
  </div>
</template>

<script setup>
import { DArrowRight, Delete, Edit, Key, User } from '@element-plus/icons-vue'
import { md5 } from 'js-md5'

const contentRef = useTemplateRef('contentRef')
const formDialog = useTemplateRef('formDialog')
const roleFormDialog = useTemplateRef('roleFormDialog')
const tableProps = [
  {label: '头像', type: 'avatar'},
  {label: '账号', prop: 'userName'},
  {label: '昵称', prop: 'nickName'},
  {label: '手机号码', prop: 'tel'},
  {label: '状态', type: 'status'},
  {label: '创建时间', prop: 'createTime'},
  {label: '操作', type: 'operate'}
]
const initPassword = ref(undefined)
const curScope = ref($store.user.scopeId)

const isCurScope = computed(() => curScope.value === $store.user.scopeId)
const contentOps = computed(() => {
  if (isCurScope.value) return {add: 'permission:user:add', update: 'permission:user:edit', delete: 'permission:user:remove'}
  else return {delete: 'permission:user:remove'}
})
const searchProps = ref([
      {label: '管理员账号', prop: 'userName', type: 'input', width: 12, labelWidth: 6},
      {label: '管理员昵称', prop: 'nickName', type: 'input', width: 12, labelWidth: 6},
      {label: '手机号码', prop: 'tel', type: 'input', width: 12, labelWidth: 6},
      {label: '账户状态', prop: 'status', type: 'select', options: $dict.normal_disable, width: 13, labelWidth: 5}
    ]
)
const roleOptions = ref([])
const formProps = computed(() => ([
  {label: '头像', prop: 'avatar', type: $formType.imageUpload('system/admin/face/', 120, 120), changeValidate: true, required: false},
  [
    {label: '账号', prop: 'userName', type: $formType.input()},
    {label: '用户密码', prop: 'password', type: $formType.password(), show: form => form.id === undefined}
  ],
  [
    {
      label: '手机号码',
      prop: 'tel',
      type: $formType.input(),
      rule: $formVerify.useVerify($formVerify.phone(false)),
      changeValidate: true
    },
    {label: '邮箱', prop: 'email', type: $formType.input(), required: false}
  ],
  [
    {label: '用户昵称', prop: 'nickName', type: $formType.input(), default: '', required: false}
  ],
  [
    {label: '状态', prop: 'status', type: $formType.radio($dict.normal_disable), default: '0', required: false}
  ],
  {label: '备注', prop: 'remark', type: $formType.textarea(), required: false}
]))

passwordInit()

function passwordInit() {
  $xl.apis.getConfigKey({
    jointUrl: '/system.user.initPassword'
  }).then(response => {
    initPassword.value = response.msg
  })
}

const roleFormProps = computed(() => ([
  {label: '角色', prop: 'roleIds', type: $formType.slot(), required: true}
]))

function handleAdd() {
  formDialog.value.open('添加用户', {password: initPassword.value})
}

function handleUpdate(id) {
  $xl.apis.getAdminUser({
    jointUrl: '/' + id
  }).then(response => {
    formDialog.value.open('修改用户', {...response.data})
  })
}

function handleDelete(id) {
  $xl.modal.confirm('确认删除该用户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    closeOnClickModal: false
  }).then(() => {
    $xl.apis.deleteAdminUser({
      jointUrl: '/' + id
    }).then(() => {
      contentRef.value.getList()
    }).catch(err => {
      $xl.modal.msgError(err)
    })
  }).catch(() => {
  })
}


function handleResetPwd(row) {
  $xl.modal.prompt('请输入"' + row.userName + '"的新密码', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    closeOnClickModal: false,
    inputPattern: /^.{5,20}$/,
    inputErrorMessage: '用户密码长度必须介于 5 和 20 之间'
  }).then(({value}) => {
    $xl.apis.resetAdminUserPassword({
      params: {
        id: row.id,
        password: md5(value)
      }
    }).then(() => {
      $xl.modal.msgSuccess('重置密码成功')
    }).catch((err) => {
      $xl.modal.msgError(err)
    })
  }).catch(() => {
  })
}

function save(res) {
  res.password = md5(res.password)
  $xl.apis.saveAdminUser({params: res}).then(() => {
    contentRef.value.getList()
    formDialog.value.close()
  }).catch(err => {
    formDialog.value.close(err)
  })
}

function update(res) {
  $xl.apis.updateAdminUser({params: res}).then(() => {
    contentRef.value.getList()
    formDialog.value.close()
  }).catch(err => {
    formDialog.value.close(err)
  })
}

function handleStatusChange(row) {
  $xl.throttle(() => {
    $xl.modal.confirm('确认修改用户状态吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      closeOnClickModal: false
    }).then(() => {
      $xl.apis.updateAdminUserStatus({
        params: {
          id: row.id,
          status: row.status
        }
      }).then(() => {
        contentRef.value.getList()
        $xl.modal.msgSuccess('修改用户状态成功')
      }).catch(() => {
        row.status = row.status === '0' ? '1' : '0'
      })
    }).catch(() => {
      row.status = row.status === '0' ? '1' : '0'
    })
  })
}

function handleCommand(command, row) {
  switch (command) {
    case 'handleResetPwd':
      handleResetPwd(row)
      break
    case 'handleAuthRole':
      handleAuthRole(row)
      break
    default:
      break
  }
}

function handleAuthRole(row) {
  $xl.apis.getAdminUserRoles({
    jointUrl: '/' + row.id
  }).then(response => {
    roleOptions.value = response.roles
    const roleIds = []
    response.roles.forEach(item => {
      if (item.flag === true) {
        roleIds.push(item.id)
      }
    })
    roleFormDialog.value.open('分配角色', {userId: row.id, roleIds: roleIds})
  })
}

function saveRole(res) {
  $xl.apis.insertAuthRole({
    params: {
      userId: res.userId,
      roleIds: res.roleIds
    }
  }).then(() => {
    roleFormDialog.value.close()
  }).catch(err => {
    roleFormDialog.value.close(err)
  })
}
</script>

<style scoped>
.operation-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
}
</style>

